package rpc.proxy;

import rpc.common.MyInvocation;
import rpc.common.MyURL;
import rpc.loadbalance.MyLoadBalance;
import rpc.netty.client.MyNettyClient;
import rpc.register.MyRemoteRegister;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 自定义代理工厂
 */
public class MyProxyFactory {
    /**
     * 获取代理对象
     */
    public static <T> T getProxy(Class<?> interfaceClass) {
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, (proxy, method, args) -> {
            //构建调用存储
            MyInvocation myInvocation = new MyInvocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);

            //服务发现
            List<MyURL> myURLs = MyRemoteRegister.get(interfaceClass.getName());

            //负载均衡
            MyURL myURL = MyLoadBalance.random(myURLs);

            String result = null;
            String errorMessage = null;
            //服务容错
            for (int i = 1; i < 4; i++) {
                try {
                    //服务调用
                    result = MyNettyClient.send(myURL.getHostname(), myURL.getPort(), myInvocation);
                } catch (Exception e) {
                    System.out.println("服务调用异常，第" + i + "次");
                    errorMessage = "服务调用异常，请稍后再试";
                }

                if (result != null) {
                    break;
                }
            }

            if (result == null) {
                return errorMessage;
            }

            return result;
        });
        return (T) proxyInstance;
    }
}
